#include "LogFile.h"

#include "../FileUtils.h"

#include <cstdio>
#include <unistd.h>

namespace detail {
    string getHostname() {
        char buf[256];
        if (::gethostname(buf, sizeof buf) == 0) {
            buf[sizeof(buf) - 1] = '\0';
            return buf;
        } else {
            return "unknownhost";
        }
    }

    pid_t getPid() {
        return ::getpid();
    }
}


LogFile::LogFile(const string &basename,
                 off_t rollSize,
                 bool threadSafe,
                 int flushInterval,
                 int checkEveryN)
        : basename_(basename),
          rollSize_(rollSize),
          flushInterval_(flushInterval),
          checkEveryN_(checkEveryN),
          count_(0),
          mutex_(threadSafe ? new MutexLock : nullptr),
          startOfPeriod_(0),
          lastRoll_(0),
          lastFlush_(0) {
    //   assert(basename.find('/') == string::npos);
    rollFile();
}

LogFile::~LogFile() = default;

void LogFile::append(const char *logline, int len) {
    if (mutex_) {
        MutexLockGuard lock(*mutex_);
        // 锁不为空就加锁再进行操作
        append_unlocked(logline, len);
    } else {
        append_unlocked(logline, len);
    }
}

void LogFile::flush() {
    if (mutex_) {
        MutexLockGuard lock(*mutex_);
        file_->flush();
    } else {
        file_->flush();
    }
}

void LogFile::append_unlocked(const char *logline, int len) {
    file_->append(logline, len);
    // 追加日志信息到文件后
    if (file_->writtenBytes() > rollSize_) {
        rollFile();
        // 当当前文件写入的数据大小大于设定的切换大小就切换文件
    } else {
        ++count_;
        if (count_ >= checkEveryN_) {
            // 当日志记录的次数超过设定值就写入日志到文件中
            count_ = 0;
            time_t now = ::time(nullptr);
            time_t thisPeriod_ = now / kRollPerSeconds_ * kRollPerSeconds_;
            if (thisPeriod_ != startOfPeriod_) {
                rollFile();
            } else if (now - lastFlush_ > flushInterval_) {
                lastFlush_ = now;
                file_->flush();
                // 写入日志
            }
        }
    }
}

bool LogFile::rollFile() {
    time_t now = 0;
    string filename = getLogFileName(basename_, &now);
    time_t start = now / kRollPerSeconds_ * kRollPerSeconds_;

    if (now > lastRoll_) {
        lastRoll_ = now;
        lastFlush_ = now;
        startOfPeriod_ = start;
        file_.reset(new FileUtils::AppendFile(filename));
        // 重新设定文件流
        return true;
    }
    return false;
}

string LogFile::getLogFileName(const string &basename, time_t *now) {
    string filename;
    filename.reserve(basename.size() + 64);
    filename = basename;

    char timebuf[32];
    struct tm tm;
    *now = time(NULL);
    gmtime_r(now, &tm); // FIXME: localtime_r ?
    strftime(timebuf, sizeof timebuf, ".%Y%m%d-%H%M%S.", &tm);
    filename += timebuf;
    // 文件名凭借时间
    filename += detail::getHostname();

    char pidbuf[32];
    snprintf(pidbuf, sizeof pidbuf, ".%d", detail::getPid());
    filename += pidbuf;
    filename += ".log";

    // 文件名格式 : basename.创建时间.主机名称.进程名.log
    return filename;
}